from utils.GetKeyword import GetKeyword
from utils.SendMethod import SendMethod


class MemberInterface:
    def __init__(self, url):
        self.url = url

    # 获取验证码
    def get_auth_code(self, telephone):
        url = self.url + '/sso/getAuthCode'
        payload = {'telephone': telephone}
        return SendMethod.send_method(method='get', url=url, params=payload)

    # 提取验证码
    def get_verify_code(self, telephone):
        response = self.get_auth_code(telephone)
        return GetKeyword.get_keyword(response, 'data')

    # 注册
    def register(self, payload):
        url = self.url + '/sso/register'
        return SendMethod.send_method(method='post', url=url, data=payload)

    # 登录
    def login(self, payload):
        url = self.url + '/sso/login'
        return SendMethod.send_method(method='post', url=url, data=payload)

    # 获取token
    def get_member_token(self, payload):
        response = self.login(payload)
        token = GetKeyword.get_keyword(response, 'token')
        return {'Authorization': f'Bearer {token}'}

    # 刷新token
    def refresh_token(self, payload):
        token_login = self.get_member_token(payload)
        print(token_login)
        url = self.url + '/sso/refreshToken'
        result = SendMethod.send_method(method='get', url=url, headers=token_login)
        token = GetKeyword.get_keyword(result, 'token')
        return {'Authorization': f'Bearer {token}'}

    # 会员修改密码
    def change_password(self, data):
        # 先登录
        self.login(payload)
        url = self.url + '/sso/updatePassword'
        return SendMethod.send_method(method='post', url=url, data=data)

    # 获取会员信息
    def get_info(self, payload, params):
        # 获取token
        token = self.get_member_token(payload)
        url = self.url + '/sso/info'
        return SendMethod.send_method(method='get', url=url, params=params, headers=token)


if __name__ == '__main__':
    member = MemberInterface(url='http://47.108.206.100:8085')
    # telephone = {'telephone': '15884756496'}
    # payload = {
    #     'username': 'yyn1234',
    #     'password': '123456',
    #     'telephone': telephone.get('telephone'),
    #     'authCode': member.get_verify_code(telephone.get('telephone'))
    # }
    # print(member.register(payload=payload))
    # payload = {
    #     'username': 'yyn1234',
    #     'password': '123456',
    # }
    # data = {
    #     'password': '12345678',
    #     'telephone': '15884756496',
    #     'authCode': member.get_verify_code('15884756496')
    # }
    # print(member.login(payload))
    # print(member.get_member_token(payload))
    # print(member.get_member_token(payload))
    # print(member.refresh_token(payload))
    # print(member.change_password(data=data)
    payload = {
        'username': 'yyn1234',
        'password': '12345678'
    }
    params = {
        'name': 'yyn1234'
    }
    print(member.get_info(payload=payload, params=params))
